package com.sxz.sbs.module.client;

import android.Manifest;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.content.res.Resources;
import android.database.Cursor;
import android.net.Uri;
import android.provider.CallLog;
import android.support.design.widget.TabLayout;
import android.support.v4.app.ActivityCompat;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.Log;
import android.util.TypedValue;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.PermissionUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.sxz.sbs.R;
import com.sxz.sbs.applibrary.state.StateLayout;
import com.sxz.sbs.base.BaseActivity;
import com.sxz.sbs.constant.IntentConstant;
import com.sxz.sbs.constant.TypeConstant;
import com.sxz.sbs.event.RecoverPhoneEvent;
import com.sxz.sbs.http.retrofit.HttpParamMap;
import com.sxz.sbs.module.client.adapter.ClientAdapter;
import com.sxz.sbs.module.client.bean.CallBean;
import com.sxz.sbs.module.client.bean.ClientListBean;
import com.sxz.sbs.module.client.presenter.ClientListPresenter;
import com.sxz.sbs.module.client.view.ClientListView;
import com.sxz.sbs.router.RouterUrl;
import com.sxz.sbs.util.CommonTabLayoutTitle;
import com.sxz.sbs.widget.MultiplePhoneDialog;
import com.sxz.sbs.widget.StallAlertDialog;
import com.sxz.sbs.widget.UpdateRecordDialog;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.lang.reflect.Field;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

import static android.telephony.TelephonyManager.CALL_STATE_IDLE;

/**
 * @author hp
 * @date 2018/1/9
 * 客户列表（所有客户，意向客户，已交定金客户，已成客户）
 */
@Route(path = RouterUrl.COUSTOM_MANAGE)
public class ClientActivity extends BaseActivity<ClientListPresenter> implements ClientListView {

    @Autowired
    public String txt_Para;
    @BindView(R.id.tv_nav_title)
    TextView tvTitle;
    @BindView(R.id.stateLayout)
    StateLayout stateLayout;

    @BindView(R.id.refreshLayout)
    SwipeRefreshLayout refreshLayout;
    @BindView(R.id.iv_title_standby)
    ImageView ivTitleRight;
    @BindView(R.id.iv_title_left_img)
    ImageView ivTitleLeft;
    /**
     * 客户列表
     */
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.tabLayout)
    TabLayout tabLayout;
    private int currentPage = 1;
    private ClientAdapter clientAdapter;
    private List<ClientListBean.ListBean> mlist = new ArrayList<>();
    private CommonTabLayoutTitle commonTabLayoutTitle = new CommonTabLayoutTitle();
    private int valStartLevel = 0;
    private int valType = 0;
    private int valStatus = 0;
    private String mkeyWords = "";
    private String callPhone = "";
    private Intent phoneIntent;
    private BroadcastReceiver callReceiver;
    private TelephonyManager tm;
    private boolean isCall;
    private String endTime = "";
    private ClientListBean.ListBean currentItem;
    private IntentFilter intentFilter;
    private boolean isOutLine;
    private boolean isRegistered = true;
    private boolean isAll = false;

    /**
     * asdasdasd
     */
    @Override
    protected void init() {
        ARouter.getInstance().inject(this);
        EventBus.getDefault().register(this);
        commonTabLayoutTitle.setTabLayoutTitle(ClientActivity.this, txt_Para, tabLayout, 0);
        callReceiver = new CallReceiver();
        intentFilter = new IntentFilter("call_action");
        registerReceiver(callReceiver, intentFilter);
        String numbers = txt_Para;
        Log.e("Client", numbers);
        if (TextUtils.isEmpty(numbers)) {
            isAll = true;
        } else {
            String[] strs = numbers.split("\\&");
            if (strs.length > 0) {
                isAll = false;
                valType = Integer.valueOf(strs[0].split("=")[1]);
                if (strs.length >= 1) {
                    valStatus = Integer.valueOf(strs[1].split("=")[1]);
                }
            }
        }
        /**
         * 反射设置下滑线的宽度
         */
        tabLayout.post(new Runnable() {
            @Override
            public void run() {
                setIndicator(tabLayout, 0, 0);
            }
        });
        tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                String str = tab.getText().toString();
                currentPage = 1;
                if (str.equals("全部")) {
                    valStartLevel = 0;
                    getData(mkeyWords);
                } else if (str.equals("一星")) {
                    valStartLevel = 1;
                    getData(mkeyWords);
                } else if (str.equals("二星")) {
                    valStartLevel = 2;
                    getData(mkeyWords);
                } else if (str.equals("三星")) {
                    valStartLevel = 3;
                    getData(mkeyWords);
                } else if (str.equals("四星")) {
                    valStartLevel = 4;
                    getData(mkeyWords);
                } else if (str.equals("五星")) {
                    valStartLevel = 5;
                    getData(mkeyWords);
                }
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });
        refreshLayout.setColorSchemeResources(R.color.color_main);
        refreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                mkeyWords = "";
                currentPage = 1;
                getData(mkeyWords);
            }
        });
        refreshLayout.setRefreshing(true);
        clientAdapter = new ClientAdapter(mlist);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        recyclerView.setAdapter(clientAdapter);
        clientAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                Intent intent = new Intent(ClientActivity.this, ClientDetailsActivity.class);
                intent.putExtra(IntentConstant.CUSTOM_ID, mlist.get(position).getId());
                intent.putExtra("txt_para", txt_Para);
                startActivity(intent);
                closeRes();
            }
        });

        clientAdapter.setOnLoadMoreListener(new BaseQuickAdapter.RequestLoadMoreListener() {
            @Override
            public void onLoadMoreRequested() {
                currentPage++;
                getData(mkeyWords);
            }
        }, recyclerView);
        clientAdapter.setOnClientClickListener(new ClientAdapter.OnClientClickListener() {
            @Override
            public void onItemCallPhone(View view, final ClientListBean.ListBean item) {
                currentItem = item;
                PermissionUtils.permission("android.permission.CALL_PHONE", "android.permission.READ_CALL_LOG").callback(new PermissionUtils.SimpleCallback() {
                    @Override
                    public void onGranted() {
                        if (!TextUtils.isEmpty(item.getTxt_Phone())) {
                            String[] phoneArr = item.getTxt_Phone().split("\\,");
                            if (phoneArr.length <= 0) {
                                ToastUtils.showShort("无手机号");
                                return;
                            }
                            if (phoneArr.length > 0 && phoneArr.length <= 1) {
                                if (!TextUtils.isEmpty(phoneArr[0])) {
                                    callPhone = phoneArr[0];
                                    new StallAlertDialog.Builder(ClientActivity.this)
                                            .showTitle(false)
                                            .setMessage(callPhone)
                                            .setPositiveButton("呼叫", new StallAlertDialog.OnPositiveListener() {
                                                @Override
                                                public void onPositiveClick(View view) {
                                                    phoneIntent = new Intent("call_action");
                                                    sendBroadcast(phoneIntent);
                                                    Intent intent = new Intent();
                                                    intent.setAction(Intent.ACTION_CALL);
                                                    intent.setData(Uri.parse("tel:" + callPhone));
                                                    startActivity(intent);

                                                }
                                            }).create().show();
                                } else {
                                    ToastUtils.showShort("无手机号");
                                }
                            } else if (phoneArr.length > 1) {
                                List<String> phones = new ArrayList<String>();
                                for (int i = 0; i < phoneArr.length; i++) {
                                    if (!TextUtils.isEmpty(phoneArr[i])) {
                                        phones.add(phoneArr[i]);
                                    }
                                }
                                MultiplePhoneDialog dialog = new MultiplePhoneDialog(ClientActivity.this, phones);
                                dialog.setOnChosePhoneListener(new MultiplePhoneDialog.OnChosePhoneListener() {
                                    @Override
                                    public void onSelectPhone(String phone) {
                                        callPhone = phone;
                                        phoneIntent = new Intent("call_action");
                                        sendBroadcast(phoneIntent);
                                        Intent intent = new Intent();
                                        intent.setAction(Intent.ACTION_CALL);
                                        intent.setData(Uri.parse("tel:" + callPhone));
                                        startActivity(intent);
                                    }
                                });
                                dialog.show();
                            }
                        } else {
                            ToastUtils.showShort("无手机号");
                        }
                    }

                    @Override
                    public void onDenied() {
                        ToastUtils.showShort("请授予打电话和读取通话记录权限");
                    }
                }).request();


            }

            @Override
            public void onItemEditSchedule(View view, ClientListBean.ListBean item) {
                Intent intent = new Intent(ClientActivity.this, ClientEvaluateActivity.class);
                intent.putExtra("clientid", item.getId());
                intent.putExtra("starnum", item.getValStartLevel() + "");
                startActivity(intent);
            }
        });
    }


    @OnClick({R.id.iv_title_standby, R.id.iv_title_left_img})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_title_standby:
                startActivity(AddClientActivity.class);
                break;
            case R.id.iv_title_left_img:
                Intent intent = new Intent(ClientActivity.this, ClientSearchActivity.class);
                // 带返回数据启动Activity
                startActivityForResult(intent, 110);
                break;
            default:
                break;
        }
    }

    /**
     * 获取回传的数据
     * <p>
     * int requestCode 请求码 int resultCode 结果码 Intent data 意图(带着返回参数)
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 110 && resultCode == RESULT_OK) {
            // 为图片控件设置内容
            if (data.getStringExtra("strSearch") != null) {
                mkeyWords = data.getStringExtra("strSearch");
            }
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (!isOutLine) {
            currentPage = 1;
            getData(mkeyWords);
        }
        isOutLine = false;
    }

    private class CallReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            System.out.println("action" + intent.getAction());
            //如果是去电
            if (!intent.getAction().equals(Intent.ACTION_NEW_OUTGOING_CALL)) {
                tm = (TelephonyManager) context.getSystemService(Service.TELEPHONY_SERVICE);
                tm.listen(listener, PhoneStateListener.LISTEN_CALL_STATE);
            }
        }
    }

    PhoneStateListener listener = new PhoneStateListener() {
        @Override
        public void onCallStateChanged(int state, String incomingNumber) {
            //注意，方法必须写在super方法后面，否则incomingNumber无法获取到值。
            super.onCallStateChanged(state, incomingNumber);
            switch (state) {
                case CALL_STATE_IDLE:
                    isOutLine = true;
                    if (isCall) {
                        isCall = false;
                        try {
                            Thread.sleep(1000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        getCallRecord();
                    }
                    break;
                case TelephonyManager.CALL_STATE_OFFHOOK:
                    isCall = true;
                    break;
                case TelephonyManager.CALL_STATE_RINGING:
                    break;
                default:
                    break;
            }
        }
    };

    private void getCallRecord() {
        ContentResolver resolver = getContentResolver();
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_CALL_LOG) != PackageManager.PERMISSION_GRANTED) {
            return;
        }
        Cursor cursor = resolver.query(CallLog.Calls.CONTENT_URI,
                new String[]{CallLog.Calls.CACHED_NAME
                        , CallLog.Calls.NUMBER
                        , CallLog.Calls.DATE
                        , CallLog.Calls.DURATION
                        , CallLog.Calls.TYPE}
                , CallLog.Calls.NUMBER + "=" + callPhone, null, CallLog.Calls.DEFAULT_SORT_ORDER// 按照时间逆序排列，最近打的最先显示
        );
        // 3.通过Cursor获得数据
        List<CallBean> list = new ArrayList<>();
        while (cursor.moveToNext()) {
            String name = cursor.getString(cursor.getColumnIndex(CallLog.Calls.CACHED_NAME));
            String number = cursor.getString(cursor.getColumnIndex(CallLog.Calls.NUMBER));
            long dateLong = cursor.getLong(cursor.getColumnIndex(CallLog.Calls.DATE));
            String date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(dateLong));
            int duration = cursor.getInt(cursor.getColumnIndex(CallLog.Calls.DURATION));
            int type = cursor.getInt(cursor.getColumnIndex(CallLog.Calls.TYPE));
            String typeString = "";
            switch (type) {
                case CallLog.Calls.INCOMING_TYPE:
                    typeString = "打入";
                    break;
                case CallLog.Calls.OUTGOING_TYPE:
                    typeString = "打出";
                    break;
                case CallLog.Calls.MISSED_TYPE:
                    typeString = "未接";
                    break;
                default:
                    break;
            }
            CallBean callBean = new CallBean();
            callBean.setName((name == null) ? "未备注联系人" : name);
            callBean.setNumber(number);
            callBean.setDate(date);
            callBean.setDuration(duration);
            callBean.setType(typeString);
            list.add(callBean);
        }
        cursor.close();

        if (list != null && list.size() > 0) {
            //  查询出了数据
            final CallBean callBean = list.get(0);
            if (callBean.getDuration() > 0) {
                if (txt_Para.equals("valType=1&valStatus=0") || txt_Para.equals("valType=3&valStatus=0")) {
                    UpdateRecordDialog dialog = new UpdateRecordDialog(this);
                    dialog.setOnUpdateDialogListener(new UpdateRecordDialog.OnUpdateDialogListener() {
                        @Override
                        public void onClose(UpdateRecordDialog dialog) {
                            addCallRecord(callBean);
                        }

                        @Override
                        public void onToIntent(UpdateRecordDialog dialog) {
                            addCallRecord(callBean);
                            HashMap<String, Object> map = HttpParamMap.getParamMap();
                            map.put("customId", currentItem.getId());
                            map.put("valType", TypeConstant.VAL_TYPE_HAVE);
                            mPresenter.getAddIntentionClient(map);
                        }

                        @Override
                        public void onToUpdate(UpdateRecordDialog dialog) {
                            addCallRecord(callBean);
                            Intent intent = new Intent(ClientActivity.this, ClientEvaluateActivity.class);
                            intent.putExtra("clientid", currentItem.getId());
                            intent.putExtra("starnum", currentItem.getValStartLevel() + "");
                            startActivity(intent);
                        }
                    });
                    dialog.show();
                } else {
                    new StallAlertDialog.Builder(this).showTitle(false)
                            .setMessage("是否需要更新跟进记录？")
                            .setCancelable(false)
                            .setCanceledOnTouchOutside(false)
                            .setNegativeButton(new StallAlertDialog.OnNegativeListener() {
                                @Override
                                public void onNegativeClick(View view) {
                                    addCallRecord(callBean);
                                }
                            })
                            .setPositiveButton(new StallAlertDialog.OnPositiveListener() {
                                @Override
                                public void onPositiveClick(View view) {
                                    addCallRecord(callBean);
                                    Intent intent = new Intent(ClientActivity.this, ClientEvaluateActivity.class);
                                    intent.putExtra("clientid", currentItem.getId());
                                    intent.putExtra("starnum", currentItem.getValStartLevel() + "");
                                    startActivity(intent);
                                }
                            })
                            .create().show();
                }


            }

        }

    }

    /**
     * 新增通话记录
     */
    private void addCallRecord(CallBean callBean) {
        endTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
        HashMap<String, Object> map = HttpParamMap.getParamMap();
        map.put("customId", currentItem.getId());
        map.put("callBeginTime", callBean.getDate());
        map.put("callEndTime", endTime);
        mPresenter.addCallRecord(map);

    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_client;
    }

    @Override
    protected ClientListPresenter createPresenter() {
        return new ClientListPresenter();
    }

    @Override
    public void onClientListSuccess(ClientListBean data) {

        if (mIsLive && data != null) {
            tvTitle.setText(tvTitle.getText().toString().split("\\(")[0] + "(" + data.getTotalRow() + ")");
            refreshLayout.setRefreshing(false);
            if (data.getList() != null && data.getList().size() > 0) {
                stateLayout.showContent();
                if (currentPage == 1) {
                    mlist.clear();
                    mlist.addAll(data.getList());
                    clientAdapter.notifyDataSetChanged();
                } else {
                    mlist.addAll(data.getList());
                    clientAdapter.notifyDataSetChanged();
                }
                clientAdapter.loadMoreComplete();
            } else {
                if (currentPage == 1) {
                    mlist.clear();
                    clientAdapter.notifyDataSetChanged();
                    //  数据为空
                    stateLayout.showEmpty();
                } else {
                    clientAdapter.loadMoreEnd();
                    clientAdapter.notifyDataSetChanged();
                }
            }
        }
    }

    @Override
    public void onAddCallRecordSuccess() {
        currentPage = 1;
        getData(mkeyWords);
    }

    private void closeRes() {
        if (tm != null) {
            tm.listen(listener, PhoneStateListener.LISTEN_NONE);
        }
        unregisterReceiver(callReceiver);
        isRegistered = false;
    }

    @Override
    public void onAddIntentionClientSuccess() {
        ToastUtils.showShort("添加成功");
    }

    /**
     * 获取客户数据
     */
    private void getData(String keyWords) {
        /**
         pageNumber	int	是	页码
         pageSize	int	是	每页数量
         keyWords	string	否	关键字
         valStatus	int	否	当前状态
         valType	int	否	是否意向客户0所有 1分配客户 2意向客户
         valStartLevel	int	否	星级
         orderBy	string	否	desc/asc 时间排序 不填默认desc
         */
        HashMap<String, Object> map = HttpParamMap.getParamMap();
        map.put("pageNumber", currentPage);
        map.put("pageSize", 10);
        map.put("keyWords", keyWords);
        if (!isAll) {
            map.put("valStatus", valStatus);
            map.put("valType", valType);
        }
        map.put("valStartLevel", valStartLevel);
        map.put("orderBy", "desc");
        mPresenter.getClientList(map);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onRecoverEvent(RecoverPhoneEvent event) {
        LogUtils.e("恢复中...");
        callReceiver = new CallReceiver();
        registerReceiver(callReceiver, intentFilter);
        isRegistered = true;
    }

    @Override
    protected void onDestroy() {
        if (tm != null) {

            tm.listen(listener, PhoneStateListener.LISTEN_NONE);
        }
        if (isRegistered) {
            unregisterReceiver(callReceiver);
        }
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    /**
     * 设置线的宽度
     */
    private void setIndicator(TabLayout tabs, int leftDip, int rightDip) {
        Class<?> tabLayout = tabs.getClass();
        Field tabStrip = null;
        try {
            tabStrip = tabLayout.getDeclaredField("mTabStrip");
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        }

        tabStrip.setAccessible(true);
        LinearLayout llTab = null;
        try {
            llTab = (LinearLayout) tabStrip.get(tabs);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }

        int left = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, leftDip, Resources.getSystem().getDisplayMetrics());
        int right = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, rightDip, Resources.getSystem().getDisplayMetrics());

        for (int i = 0; i < llTab.getChildCount(); i++) {
            View child = llTab.getChildAt(i);
            child.setPadding(0, 0, 0, 0);
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(0, LinearLayout.LayoutParams.MATCH_PARENT, 1);
            params.leftMargin = left;
            params.rightMargin = right;
            child.setLayoutParams(params);
            child.invalidate();
        }
    }
}
